local skynet = require "skynet"
require "skynet.manager"    -- import skynet.register
local mysql = require "mysql"


local db_pool = {}

--轮询用的db index，永远都是增长的
local db_use_index = 1 

local command = {}

--[[
    callstr:  请求的查询名，只能是call语句
    res_sql: 第二句访问字串, 是否要求有返回值     
    dbindex: 请求的db对列，有数据库访问严格前后关系
             可使用单一队列， 如为 nil ，轮询访问

    return: 返回两个结果集, 对于有返回参数的存贮过程，只需使用第二个结果集


    local sqlstr = "call pr_MatchChagre("..UserId..","..MatchConf["pay_type"]..","..MatchConf["pay_num"]..",@ReturnVal);"
    local res_sql = "select @ReturnVal;"
    local res1, res2 = db.call(sqlstr, res_sql)
    
    print(res2[1]['@ReturnVal'])

--]]

function command.query(callstr, res_sql, dbindex)

    if #db_pool == 0 or callstr == nil then
        skynet.error("command.query find db_pool zero")
        return nil
    end
    --skynet.error("[dbser] query dbindex ",dbindex)
    if dbindex == nil then
       dbindex = db_use_index
       db_use_index = db_use_index + 1
    end
    --skynet.error("[dbser] query dbindex FFFFFF",dbindex,)
    local index = math.fmod(tonumber(dbindex), #db_pool)
    local index = index + 1
    
   -- skynet.error("db query use index:"..index.." max db pool:"..#db_pool)
   -- skynet.error("db query:"..callstr)

    local db = db_pool[index]
    local db_res = db:query(callstr)
    local sql_result = nil
    if res_sql then
        sql_result = db:query(res_sql)                                 --如果有查询第二结果，则返回第二个结果
    end

    return db_res,sql_result
end


function command.runService(conf, max_db)

    skynet.error("runService db max_db:"..max_db)
    for i=1, max_db do

        local db = mysql.connect({
                host        = conf.host,
                port        = tonumber(conf.port),
                database    = conf.database,
                user        = conf.user,
                password    = conf.password,
                max_packet_size =  tonumber(conf.max_packet_size),
                on_connect  = function(dbself)
                                 dbself:query("set charset utf8") 
                                 end,
        })

        table.insert(db_pool, db)
        skynet.error("db_pool num="..#db_pool)
    end
    skynet.error("runService end max_db:"..max_db)
end

function OnTimerFunction()
	skynet.fork(function()
        while true do
            
            skynet.sleep(100)    
        end
    end)
end

skynet.start(function()
    skynet.register(".powerdb")
	skynet.error("start power_db server")
	skynet.dispatch("lua", function(session, address, cmd, ...)
		local f = command[cmd]
		if f then
			skynet.ret(skynet.pack(f(...)))
		else
			error(string.format("Unknown command %s", cmd))
		end
	end)

    OnTimerFunction()
end)
